package com.chuangke.metadata.service.impl;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.toolkit.SqlRunner;
import com.chuangke.common.constant.Masks;
import com.chuangke.metadata.constant.MetaDataConstant;
import com.chuangke.metadata.entity.SysGridColumn;
import com.chuangke.metadata.entity.SysGridModel;
import com.chuangke.metadata.service.SysGridModelService;
import com.chuangke.metadata.service.SysGridService;
import com.chuangke.metadata.service.SysGridlFormulaService;

import cn.hutool.core.util.StrUtil;

@Service
public class SysGridServiceImpl implements SysGridService{
	
	@Autowired
	private SysGridlFormulaService sysGridlFormulaService;

	@Autowired
	private SysGridModelService sysGridModelService;

	@Override
	public void copy(SysGridModel targetModel, String sourceModelId) {
		SysGridModel model = sysGridModelService.load(sourceModelId) ;
		SysGridModel formulaModel = sysGridlFormulaService.loadFormulaByModelId(sourceModelId,false) ;
		model.setFormulas(formulaModel.getFormulas());
		model.setVars(formulaModel.getVars());
		
		model.setId(targetModel.getId());
		model.setName(targetModel.getName());
		model.setCategory(targetModel.getCategory());
		model.setRemarks(targetModel.getRemarks());
		model.setSort(targetModel.getSort());
		
		sysGridModelService.save(model) ;
		sysGridlFormulaService.save(model);
	}

	@Override
	public void init(String dataBase, String tableName,String moudleId,String modelId,String modelName) {
		SysGridModel model = new SysGridModel();
		model.setDelFlag(Masks.BOOL_NO);
		model.setId(modelId);
		model.setName(modelName);
		model.setMoudleId(moudleId);
		model.setType(MetaDataConstant.GRID_MODEL_TYPE_STATIC_TABLE);
		String sql = "select table_name,column_name,column_comment,data_type,column_default from information_schema.columns WHERE TABLE_SCHEMA = {0} and table_name={1} " ;
		List<Map<String, Object>> list = SqlRunner.db().selectList(sql.toString(), dataBase,tableName);

		List<SysGridColumn> columns = list.stream().map(map -> {
			SysGridColumn column = new SysGridColumn();
			column.setModelId(modelId);
			column.setProp(StrUtil.toCamelCase(map.get("column_name").toString()));
			column.setLabel(map.get("column_comment").toString());
			column.setDelFlag(Masks.BOOL_NO);
			column.setAlign("left");
			column.setWidth("150");
			return column ;
		}).collect(Collectors.toList()) ;
		model.setColumns(columns);

		sysGridModelService.save(model) ;
	}

}
